#coding=utf-8
from uliweb import expose, decorators

def __begin__():
    from uliweb import function
    return function('require_login')()
    
@expose('/ticket/questions')
class Question(object):
    def __init__(self):
        from uliweb.orm import get_model
        
        self.model = get_model('question')
        self.comment_model = get_model('questioncomment')
        self.anchor = 'questions'
        self.index = self.comment_model.c.question
        self.comment_key = 'question'
        self.list_fields_convert = {}
        self.status_choices = 'TICKET/STATUS_Q'
        self.table_id = 'question_table'
        self.status = ['1', '2', '3']
        self.query_layout = [('only_mine', 'tx', 'kfzx', 'closed'), 
            ('title', 'status', 'priority'), 
            ('requirement_title', 'task_title','care_level'),
            ('submitter', 'assigned', 'need_discuss')]
        
    def add(self):
        """
        添加新问题
        """
        
        from uliweb.utils.generic import AddView
        from uliweb.orm import get_model
        
        System = get_model('system')
        
        data = {}
        if request.GET.get('requirement', None):
            data['requirement'] = int(request.GET.get('requirement'))
            url = '/requirements/%d#%s' % (data['requirement'], self.anchor)
            Requirement = get_model('requirement')
            req = Requirement.get(data['requirement'])
            data['tx'] = req._tx_
            meta = 'AddReqForm'
            
        if request.GET.get('task', None):
            Task = get_model('tasks_develop')
            data['task'] = int(request.GET.get('task'))
            task = Task.get(int(data['task']))
            data['requirement'] = task._requirement_
            url = '/tasks/develop/%d#%s' % (data['task'], self.anchor)
            req = task.requirement
            data['tx'] = req._tx_
            data['kfzx'] = task.task_sys._kfzx_
            data['owner_sys'] = task._task_sys_
            meta = 'AddForm'
            
        data['owner'] = request.user.id
        
        def pre_save(data):
            if data.get('owner_sys'):
                sys = System.get(int(data.get('owner_sys')))
                data['kfzx'] = sys._kfzx_
                
        def post_created_form(fcls, model):
            if not request.GET.get('task', None):
                fcls.owner_sys.query = req.systems.all()
            fcls.systems.query = req.systems.all()
        
        view = AddView(self.model, url, default_data=data, meta=meta,
            post_created_form=post_created_form, pre_save=pre_save)
        return view.run()
    
    def _create_query(self, url):
        """
        创建查询View
        """
        from uliweb.orm import get_model
        from uliweb.utils.generic import QueryView
        from uliweb.form import UnicodeField, SelectField
        from plugs.ui.jquery.jqcombobox.widgets import JQComboBoxField
        from plugs.ui.jquery.uimultiselect.widgets import UIMultiSelectField
        from query.forms import QueryForm
        from uliweb.utils.generic import ReferenceSelectField
        
#        def get_record(model):
#            def _f(id):
#                from uliweb.orm import get_model
#                
#                if id:
#                    obj = get_model(model).get(int(id))
#                    if obj:
#                        return [(obj.id, unicode(obj))]
#                return [('', '')]
#            return _f
        
        tx = ReferenceSelectField('tx', label='条线')
        kfzx = ReferenceSelectField('kfzx', label='开发中心')
#        Requirement = get_model('requirement')
#        requirement = JQComboBoxField(label='准开发需求', url='/requirements/query', get_record=get_record('requirement'))
        title = UnicodeField(label='标题')
        requirement_title = UnicodeField(label='准开发需求')
        task_title = UnicodeField(label='任务')
        status = UIMultiSelectField('状态', choices=settings.get_var(self.status_choices))
        closed = SelectField('显示已关闭', choices=settings.get_var('PARA/YES_NO'), default='0')
        need_discuss = SelectField('是否需要上会', choices=settings.get_var('PARA/YES_NO'))
        only_mine = SelectField('与我有关的', choices=settings.get_var('PARA/ONLY_MINE'), default='0')
        priority = SelectField('优先级', choices=settings.get_var('TICKET/PRIORITY'))
        care_level = SelectField('关注级别', choices=settings.get_var('PARA/CARE_LEVEL'))
        fields = [('need_discuss', need_discuss), ('requirement_title', requirement_title), ('task_title', task_title), ('status', status), 
            ('only_mine', only_mine), ('title', title), ('task_title', task_title),('care_level', care_level),
            ('tx', tx), ('kfzx', kfzx), ('closed', closed), ('priority', priority),
            'submitter', 'assigned'] 
        query = QueryView(self.model, ok_url=url, fields=fields, layout=self.query_layout, form_cls=QueryForm)
        return query
    
    def list(self):
        """
        问题列表
        """
        
        from uliweb.utils.generic import ListView, get_sort_field
        from uliweb.orm import get_model
        
        Requirement = get_model('requirement')
        Task = get_model('tasks_develop')
        
        type = request.GET.get('type', 'list')
        query = self._create_query(url_for(self.__class__.list))
        c = query.run()
        
        pageno = int(request.values.get('page', 1)) - 1
        rows_per_page=int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
        
        condition = None
        #process request.POST
        if request.values.get('task'):
            condition = (self.model.c.task == int(request.values.get('task'))) & condition
        if request.values.get('requirement'):
            condition = (self.model.c.requirement == int(request.values.get('requirement'))) & condition
        if c.get('only_mine') == '1':
            condition = (self.model.systems.in_(request.user.users_systems.ids()) | (self.model.c.owner == request.user.id) | self.model.c.owner_sys.in_(request.user.users_systems.ids())) & condition
        if c.get('title'):
            condition = self.model.c.title.like('%'+c['title']+'%') & condition
        if c.get('submitter'):
            condition = self.model.c.submitter.like('%'+c['submitter']+'%') & condition
        if c.get('assigned'):
            condition = self.model.c.assigned.like('%'+c['assigned']+'%') & condition
        if c.get('priority'):
            condition = (self.model.c.priority == c.get('priority')) & condition
        if c.get('need_discuss'):
            condition = (self.model.c.need_discuss == (c.get('need_discuss')=='1')) & condition
        _con = None
        if c.get('requirement_title'):
            _con = Requirement.c.title.like('%'+c['requirement_title']+'%') | Requirement.c.req_id.like('%'+c['requirement_title']+'%')
            _r = Requirement.filter(_con).values('id')
            req_ids = [x[0] for x in _r]
            if req_ids:
                condition = (self.model.c.requirement.in_(req_ids)) & condition
            else:
                condition = (self.model.c.id != self.model.c.id) & condition
        if c.get('care_level'):
            _r = Requirement.filter(Requirement.c.care_level == c.get('care_level')).values('id')
            req_ids = [x[0] for x in _r]
            if req_ids:
                condition = (self.model.c.requirement.in_(req_ids)) & condition
            else:
                condition = (self.model.c.id != self.model.c.id) & condition
            
        if c.get('task_title'):
            _r = Task.filter(Task.c.name.like('%'+c['task_title']+'%') | Task.c.task_id.like('%'+c['task_title']+'%')).values('id')
            task_ids = [x[0] for x in _r]
            if task_ids:
                condition = (self.model.c.task.in_(task_ids)) & condition
            else:
                condition = (self.model.c.id != self.model.c.id) & condition
                
        if c.get('tx'):
            condition = (self.model.c.tx == c.get('tx')) & condition
        if c.get('kfzx'):
            condition = (self.model.c.kfzx == c.get('kfzx')) & condition
        if c.get('status'):
            status = c.get('status')
        else:
            status = self.status
        if c.get('closed') == '1':
            if 'F' not in status:
                status.append('F')
                
        condition = self.model.c.status.in_(status) & condition
        condition = (self.model.c.requirement==Requirement.c.id) & condition
            
        order_by = get_sort_field(self.model) or []
        order_by.insert(0, Requirement.c.care_level.desc())

        def need_discuss(b, obj):
            if b:
                return '<div class="ui-icon ui-icon-check"></div>'
            else:
                return '<div class="ui-icon ui-icon-closethick"></div>'
        
        def title(value, obj):
            return '<a href="/ticket/%s/view/%d" target="_blank">%s</a>' % (self.anchor, obj.id, value)
        
        def care_level(value, obj):
            return obj.requirement.get_display_value('care_level')
        
        fields_convert_map = {'need_discuss':need_discuss, 'title':title, 'care_level':care_level}
        fields_convert_map.update(self.list_fields_convert)
        view = ListView(self.model, condition=condition, pagination=(type!='json'),
            table_width=False, fields_convert_map=fields_convert_map, id=self.table_id,
            order_by=order_by, rows_per_page=rows_per_page, pageno=pageno)
        if type == 'json':
            if self.model.filter(condition).count() == 0:
                return json({'table':'', 'info':{'total':0}})
            return json(view.run(head=True, body=True))
        else:
            if 'data' in request.values:
                return json(view.json())
            elif 'download' in request.values:
                def download_id(value, obj):
                    return '<a href="%s/ticket/%s/view/%s">%s</a>' % (settings.PARA.DOMAIN, self.anchor, value, value)
                def need_discuss(b, obj):
                    if obj.need_discuss:
                        return u'是'
                    else:
                        return u'否'
                
                fields_convert_map = {'id':download_id,'need_discuss':need_discuss}
                return view.download('%s.xls' % self.anchor, action='download', timeout=0,
                    fields_convert_map=fields_convert_map)
            else:
                result = view.run(head=True, body=False)
                result.update({'query_form':query.form, 'table':view})
                return result
        
    def view(self, id):
        """
        问题显示
        """
        
        from uliweb.utils.generic import DetailView
        from uliweb import error, response
        
        obj = self.model.get(int(id))
        if not obj:
            return error("该记录已被删除！")
        view = DetailView(self.model, obj=obj)
        return view.run()
    
    def edit(self, id):
        """
        编辑问题
        """
        
        from uliweb.utils.generic import EditView
        from uliweb.orm import get_model
        
        System = get_model('system')
        
        obj = self.model.get(int(id))
        if obj._task_:
            meta = 'EditForm'
        else:
            meta = 'EditReqForm'
            
        def pre_save(obj, data):
            if not obj._task_:
                if data.get('owner_sys'):
                    sys = System.get(int(data.get('owner_sys')))
                    data['kfzx'] = sys._kfzx_
                else:
                    data['kfzx'] = None
            
        def post_created_form(fcls, model, obj):
            if not obj._task_:
                fcls.owner_sys.query = obj.requirement.systems.all()
            fcls.systems.query = obj.requirement.systems.all()
        
        view = EditView(self.model, '/ticket/%s/view/%s' % (self.anchor, id), 
            obj=obj, post_created_form=post_created_form, meta=meta, pre_save=pre_save)
        return view.run()

    @expose('delete/<id>')
    @decorators.check_role('superuser')
    def delete(self, id):
        """
        删除问题
        """
        
        from uliweb.utils.generic import DeleteView
        from uliweb.orm import get_model
        
        comment_model = self.comment_model
        index = self.index
        
        class MyDelete(DeleteView):
            def delete(self, obj):
                comment_model.filter(index==obj.id).remove()
                obj.delete()
        
        obj = self.model.get(int(id))
        view = MyDelete(self.model, '/ticket/%s/list' % self.anchor, obj=obj)
        return view.run()
    
    def close(self, id):
        """
        关闭问题
        """
        
        from uliweb.utils.generic import DeleteView
        from uliweb.orm import get_model
        from datetime import date
        
        obj = self.model.get(int(id))
        items = []
        if not obj.solve_desc:
            items.append('解决措施')
        if items:
            return json({'success':False, 'message':'，'.join(items)+'尚未填写，不能关闭'})
        else:
            obj.status = 'F'
            obj.finish_date = date.today()
            obj.save()
            return json({'success':True, 'message':'成功关闭', 
                'data':{'status':obj.get_display_value('status').encode('utf-8'),
                'finish_date':obj.field_str(obj.finish_date)}})
        
    def add_solve(self, id):
        """
        添加解决方案
        """
        
        from uliweb.utils.generic import EditView
        
        obj = self.model.get(int(id))
        
        view = EditView(self.model, '/ticket/%s/view/%s' % (self.anchor, id), 
            obj=obj, meta='SolveForm')
        return view.run()
        
    def add_comment(self, id):
        """
        添加评论,id为对应的问题id
        """
        from uliweb.utils.generic import AddView

        view = AddView(self.comment_model, form_args={'action':request.path, 
            'html_attrs':{'id':'add_comment_form'}}, default_data={self.comment_key:int(id)})
        return view.run(json_result=True)
    
    def comments(self, id):
        """
        评论列表,id为对应的问题id
        """
        from uliweb.utils.textconvert import text2html
        from uliweb.orm import NotFound
        
        objects = []
        for i, row in enumerate(self.comment_model.filter(self.index==int(id))):
            d = row.to_dict()
            d['index'] = i + 1
            d['comment'] = text2html(d['comment'])
            try:
                d['modified_user'] = row.modified_user.username.encode('utf-8')
            except NotFound:
                d['modified_user'] = row._modified_user_
            d['cls'] = 'odd rounded'
            if bool(row._modified_user_ == request.user.id):
                d['delete'] = '<a class="del_comment" href="/ticket/%s/del_comment/%s">删除</a>' % (self.anchor, row.id)
            else:
                d['delete'] = ''
            objects.append(d)
        return json(objects)
    
    def del_comment(self, id):
        """
        删除某条评论
        """
        
        from uliweb.utils.generic import DeleteView
        
        obj = self.comment_model.get(int(id))
        
        view = DeleteView(self.comment_model, obj=obj)
        return view.run(json_result=True)
    
@expose('/ticket/risks')
class Risk(Question):
    def __init__(self):
        from uliweb.orm import get_model
        
        self.model = get_model('risk')
        self.comment_model = get_model('riskcomment')
        self.anchor = 'risks'
        self.index = self.comment_model.c.risk
        self.comment_key = 'risk'
        self.status_choices = 'TICKET/STATUS_R'
        self.table_id = 'risk_table'
        self.status = ['1', '2', '3', '4']
        self.query_layout = [('only_mine', 'tx', 'kfzx', 'closed'), 
            ('title', 'status'), 
            ('requirement_title', 'task_title','care_level'),
            ('submitter', 'assigned', 'need_discuss')]
        
        def degree(value, obj):
            return str(obj.probability * obj.serious)
        
        self.list_fields_convert = {'degree':degree}
        
    def close(self, id):
        """
        关闭风险
        """
        
        from uliweb.utils.generic import DeleteView
        from uliweb.orm import get_model
        from datetime import date
        
        obj = self.model.get(int(id))
        items = []
        if not obj.solve_desc:
            items.append('缓解计划')
        if not obj.resolusion:
            items.append('应对方案')
        if items:
            return json({'success':False, 'message':'，'.join(items)+'尚未填写，不能关闭'})
        else:
            obj.status = 'F'
            obj.save()
            return json({'success':True, 'message':'成功关闭', 
                'data':{'status':obj.get_display_value('status').encode('utf-8')}})
    
    def edit(self, id):
        """
        编辑风险
        """
        
        from uliweb.utils.generic import EditView
        from uliweb.orm import get_model
        
        System = get_model('system')
        
        obj = self.model.get(int(id))
        if obj._task_:
            meta = 'EditForm'
        else:
            meta = 'EditReqForm'
            
        def pre_save(obj, data):
            if not obj._task_:
                if data.get('owner_sys'):
                    sys = System.get(int(data.get('owner_sys')))
                    data['kfzx'] = sys._kfzx_
                else:
                    data['kfzx'] = None
            
        def post_created_form(fcls, model, obj):
            if not obj._task_:
                fcls.owner_sys.query = obj.requirement.systems.all()
            fcls.systems.query = obj.requirement.systems.all()
        
        data = {'serious':str(obj.serious), 'probability':str(obj.probability)}
        view = EditView(self.model, '/ticket/%s/view/%s' % (self.anchor, id), 
            obj=obj, post_created_form=post_created_form, meta=meta, pre_save=pre_save,
            data=data)
        return view.run()
    